//
//  YYFgsPartVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/12/17.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "YYFgsPartVC.h"

@interface YYFgsPartVC ()
{
    FallLineView *_Fallview;
    JoinFaluterView *_JoinFalutView;
    ServerUnusualView *_ServerFView;
    NothingDataView *_nothing;
    NSInteger lastID;
    NSDictionary *_paratem;
}
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation YYFgsPartVC
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.NavTitle;
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(backVC)];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"seach_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(searchCilck)];
    self.navigationItem.rightBarButtonItem = rightItem;
    _dataSource = [[NSMutableArray alloc]init];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.rowHeight = 70;
    _tableView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    //去掉多余的cell
    _tableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_tableView];
    _paratem = @{@"brId":[NSString stringWithFormat:@"%ld",self.ID],@"lastId":@0};
    [self load];
    

    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [_dataSource removeAllObjects];
        _paratem = @{@"brId":[NSString stringWithFormat:@"%ld",self.ID],@"lastId":@0};
        [self load];
    }];

    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        MslistModel *msModel = [_dataSource lastObject];
        _paratem = @{@"brId":[NSString stringWithFormat:@"%ld",self.ID],@"lastId":[NSString stringWithFormat:@"%ld",msModel.ID]};
        [self load];
    }];
    
}
- (void)endRefresh{
    [_tableView.mj_header endRefreshing];
    [_tableView.mj_footer endRefreshing];
}
- (void)load{
    //K_partMassage
   
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_partMassage parameters:_paratem progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [self endRefresh];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

                PartDataModel *model = [[PartDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        
                for (MslistModel *msModel in model.mslist) {
        
                    [_dataSource addObject:msModel];
                }
        if (_dataSource.count == 0) {
            
            _nothing = [[NothingDataView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) title:@"不好...暂时没有数据"];
            _nothing.delegate = self;
            [self.view addSubview:_nothing];
        }else{
            [_nothing removeFromSuperview];
        }
        
        [self.tableView reloadData];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        if (status >= 500) {
            _ServerFView = [[ServerUnusualView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64) AndTitle:[error userInfo][@"NSLocalizedDescription"]];
            _ServerFView.delegate = self;
            [self.view addSubview:_ServerFView];
        }else if ([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"请求超时。"]) {
            _Fallview = [[FallLineView alloc]initWithFrame:CGRectMake(0,64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _Fallview.delegate = self;
            [self.view addSubview:_Fallview];
        }else if([[error userInfo][@"NSLocalizedDescription"]isEqualToString:@"似乎已断开与互联网的连接。"]){
            _JoinFalutView = [[JoinFaluterView alloc]initWithFrame:CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64)];
            _JoinFalutView.delegate = self;
            [self.view addSubview:_JoinFalutView];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}
- (void)NothingRefresh:(UIButton *)sender{
    
    [_nothing removeFromSuperview];
    [self load];
}
-(void)JoinRefersh:(UIButton *)sender{
    [_JoinFalutView removeFromSuperview];
    [self load];
}
-(void)FallLineRefresh:(UIButton *)sender{
    [_Fallview removeFromSuperview];
    [self load];
}
-(void)ServerRefresh:(UIButton *)sender{
    [_ServerFView removeFromSuperview];
    [self load];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    MslistModel *model = _dataSource[indexPath.row];
//    NSDictionary *fontDic=@{NSFontAttributeName:[UIFont systemFontOfSize:15.0]};
//    CGSize size1=CGSizeMake(kSCREEN_WIDTH-43,0);
//    CGSize titleLabelSize=[model.discrib boundingRectWithSize:size1 options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading   attributes:fontDic context:nil].size;
//
//
//    return titleLabelSize.height+40;
//
//}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        YYpartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[YYpartCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        MslistModel *model = _dataSource[indexPath.row];
        [cell fillCellWithModel:model];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MslistModel *model = _dataSource[indexPath.row];
    PartDetailVC *vc = [[PartDetailVC alloc]init];
    vc.logId = model.logId;
    vc.number = model.numb;
    vc.unit = model.unit;
    vc.discrib = model.discrib;
    vc.time = model.tm;
    vc.storeCode = model.storeCode;
    vc.storeName = model.storeName;

    [self.navigationController pushViewController:vc animated:YES];
}
- (void)searchCilck{
    
    PartSearchVC *vc = [[PartSearchVC alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)backVC{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
